<?php

namespace App\Services;

use App\Models\Product;
use App\Models\ProductVariant;

class ProductService
{
    /**
     * 获取变体规格信息
     */
    public function getVariantSpecifications(ProductVariant $variant): array
    {
        return $variant->attributeValues()
            ->with('attribute')
            ->get()
            ->map(function ($value) {
                return [
                    'name' => $value->attribute->name,
                    'value' => $value->display_value,
                ];
            })
            ->toArray();
    }

    /**
     * 获取商品图片
     */
    public function getProductImage(Product $product, ?ProductVariant $variant): ?string
    {
        // 优先使用变体图片，其次使用商品主图
        if ($variant && $variant->images->isNotEmpty()) {
            return $variant->images->first()->image_path;
        }
        
        if ($product->images->isNotEmpty()) {
            return $product->images->first()->image_path;
        }
        
        return null;
    }

    /**
     * 检查商品是否有效
     */
    public function isProductValid(Product $product): bool
    {
        return $product->is_active && $product->stock_quantity > 0;
    }

    /**
     * 检查变体是否有效
     */
    public function isVariantValid(?ProductVariant $variant): bool
    {
        if (!$variant) {
            return true; // 单规格商品
        }

        return $variant->is_active && $variant->stock_quantity > 0;
    }

    /**
     * 获取商品价格
     */
    public function getProductPrice(Product $product, ?ProductVariant $variant): float
    {
        return $variant ? $variant->price : $product->price;
    }

    /**
     * 获取商品库存
     */
    public function getProductStock(Product $product, ?ProductVariant $variant): int
    {
        return $variant ? $variant->stock_quantity : $product->stock_quantity;
    }

    /**
     * 获取商品SKU
     */
    public function getProductSku(Product $product, ?ProductVariant $variant): string
    {
        return $variant ? $variant->sku : $product->sku;
    }

    /**
     * 获取商品名称
     */
    public function getProductName(Product $product, ?ProductVariant $variant): string
    {
        $name = $product->name;
        if ($variant && $variant->name) {
            $name .= ' - ' . $variant->name;
        }
        return $name;
    }

    /**
     * 检查商品库存是否充足
     */
    public function checkStock(Product $product, ?ProductVariant $variant, int $quantity): array
    {
        $stock = $this->getProductStock($product, $variant);
        
        if ($stock < $quantity) {
            return [
                'available' => false,
                'stock' => $stock,
                'message' => "库存不足，当前库存：{$stock}"
            ];
        }

        return [
            'available' => true,
            'stock' => $stock,
            'message' => '库存充足'
        ];
    }

    /**
     * 获取商品完整信息（用于订单/购物车）
     */
    public function getProductInfo(Product $product, ?ProductVariant $variant): array
    {
        return [
            'product_id' => $product->id,
            'variant_id' => $variant?->id,
            'name' => $this->getProductName($product, $variant),
            'sku' => $this->getProductSku($product, $variant),
            'price' => $this->getProductPrice($product, $variant),
            'stock' => $this->getProductStock($product, $variant),
            'image' => $this->getProductImage($product, $variant),
            'specifications' => $variant ? $this->getVariantSpecifications($variant) : [],
            'is_valid' => $this->isProductValid($product) && $this->isVariantValid($variant),
        ];
    }

    /**
     * 获取商品详情（用于商品详情页）
     */
    public function getProductDetails(string $slug): array
    {
        $product = Product::where('slug', $slug)
            ->with([
                'images',
                'variants.attributeValues.attribute',
                'variants.images',
                'categories'
            ])
            ->firstOrFail();

        if (!$product->is_active) {
            abort(404, '商品不存在或已下架');
        }

        // 获取所有变体
        $variants = $product->variants()
            ->where('is_active', true)
            ->with(['attributeValues.attribute', 'images'])
            ->get();

        // 处理规格信息
        $specifications = [];
        if ($product->product_type === 'multi_variant' && $variants->isNotEmpty()) {
            // 获取所有规格属性
            $attributes = $variants->flatMap(function ($variant) {
                return $variant->attributeValues->map(function ($value) {
                    return [
                        'key' => $value->attribute->name,
                        'name' => $value->attribute->name,
                        'value' => $value->display_value,
                        'attribute_id' => $value->attribute->id,
                        'value_id' => $value->id,
                    ];
                });
            })->groupBy('key');

            // 构建规格选项
            $specifications = $attributes->map(function ($values, $key) {
                $uniqueValues = $values->unique('value')->values();
                return [
                    'key' => $key,
                    'name' => $key,
                    'options' => $uniqueValues->map(function ($value) {
                        return [
                            'name' => $value['value'],
                            'value' => $value['value'],
                            'attribute_id' => $value['attribute_id'],
                            'value_id' => $value['value_id'],
                        ];
                    })->toArray()
                ];
            })->values()->toArray();
        }

        // 为产品添加规格信息
        $product->specifications = $specifications;

        // 不设置默认变体，让用户自己选择规格

        return [
            'product' => $product,
            'raw_product' => $product,
            'variants' => $variants,
        ];
    }

    /**
     * 获取相关商品
     */
    public function getRelatedProducts(Product $product): \Illuminate\Database\Eloquent\Collection
    {
        return Product::where('products.id', '!=', $product->id)
            ->where('is_active', true)
            ->whereHas('categories', function ($query) use ($product) {
                $query->whereIn('categories.id', $product->categories->pluck('id'));
            })
            ->with(['images'])
            ->limit(4)
            ->get();
    }
}